package com.chen.seckill.controller;

import com.chen.seckill.exception.GlobalException;
import com.chen.seckill.pojo.DetailVo;
import com.chen.seckill.pojo.Goods;
import com.chen.seckill.pojo.GoodsVO;
import com.chen.seckill.pojo.User;
import com.chen.seckill.resultvo.RespBean;
import com.chen.seckill.resultvo.RespBeanEnum;
import com.chen.seckill.service.IGoodsService;
import com.chen.seckill.service.IUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private IUserService userService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * Windows优化前QPS: 1432  线程数：10*1000*3
     * 页面缓存优化后， Windows优化前QPS：4339
     *
     * user参数，通过执行自定义参数校验获得（具体查看UserArgumentResolver类）
     *
     * 已经设置了页面缓存
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(User user, Model model, HttpServletRequest request, HttpServletResponse response){
//        if (StringUtils.isEmpty(ticket)){
//            return "login";
//        }
//        User user=userService.getUserByCookie(ticket,request,response);
//        //User user = (User)session.getAttribute(ticket);
//        if (user==null){
//            return "login";
//        }
        System.out.println(user+"------------------");
        ValueOperations operations = redisTemplate.opsForValue();
        String html = (String) operations.get("goodsList");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        List<GoodsVO> goodsList=goodsService.findGoodsVO();
        model.addAttribute("user",user);
        model.addAttribute("goodsList",goodsList);
        //System.out.println(goodsList);
        //return "goodsList";
        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!StringUtils.isEmpty(html)) {
            operations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 商品详情页面
     *  （添加页面缓存）
     *
     * @param user
     * @param goodsId
     * @return
     */
//    @RequestMapping(value = "/toDetail/{goodsId}",produces ="text/html;charset=utf-8")
//    @ResponseBody
//    public String toDetail(Model model, User user, @PathVariable Long goodsId,HttpServletRequest request,HttpServletResponse response){
//        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
//        //在redis中获取页面，如果不为空，则返回页面
//        String html= (String) valueOperations.get("goodsDetail:"+goodsId);
//        if (!StringUtils.isEmpty(html)){
//            return html;
//        }
//        model.addAttribute("user",user);
//        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(goodsId);
//        Date startDate = goodsVO.getStartDate();
//        Date endDate = goodsVO.getEndDate();
//        Date nowDate=new Date();
//        //秒杀状态
//        int secKillStatus=0;
//        //秒杀倒计时
//        int remainSeconds=0;
//        //秒杀还未开始
//        if (nowDate.before(startDate)){
//
//            remainSeconds= (int) ((startDate.getTime()-nowDate.getTime())/1000);
//        }
//        else if (nowDate.after(endDate)){
//            //秒杀已结束
//            secKillStatus=2;
//            remainSeconds=-1;
//        }
//        else {
//            //秒杀活动正在进行中
//            secKillStatus=1;
//            remainSeconds=0;
//        }
//        model.addAttribute("goods",goodsVO);
//        model.addAttribute("secKillStatus",secKillStatus);
//        model.addAttribute("remainSeconds",remainSeconds);
//        WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
//        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
//        if (!StringUtils.isEmpty(html)) {
//            valueOperations.set("goodsDetail:"+goodsId, html, 60, TimeUnit.SECONDS);
//        }
//        return html;
//
//    }

    /**
     * 页面静态化
     * （前后端分离架构（ajax请求）就实现了页面静态化，通过前端发送ajax请求，请求后端数据，页面跳转由前端完成）
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/toDetail/{goodsId}")
    @ResponseBody
    public RespBean toDetail(User user, @PathVariable Long goodsId){

        System.out.println(goodsId+"===================="+user);
        //model.addAttribute("user",user);
        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(goodsId);
        Date startDate = goodsVO.getStartDate();
        Date endDate = goodsVO.getEndDate();
        Date nowDate=new Date();
        //秒杀状态
        int secKillStatus=0;
        //秒杀倒计时
        int remainSeconds=0;
        //秒杀还未开始
        if (nowDate.before(startDate)){

            remainSeconds= (int) ((startDate.getTime()-nowDate.getTime())/1000);
        }
        else if (nowDate.after(endDate)){
            //秒杀已结束
            secKillStatus=2;
            remainSeconds=-1;
        }
        else {
            //秒杀活动正在进行中
            secKillStatus=1;
            remainSeconds=0;
        }
        DetailVo detailVo=new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVO(goodsVO);
        detailVo.setSecKillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);
//        model.addAttribute("goods",goodsVO);
//        model.addAttribute("secKillStatus",secKillStatus);
//        model.addAttribute("remainSeconds",remainSeconds);

        return RespBean.success(detailVo);

    }
}
